import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/app/shi/data/HistoryConfig.dart';
import 'package:eshi/app/shi/data/HistoryMarks.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/data/parse/CommentParser.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';
import 'package:eshi/app/shi/widget/AppTextWidget.dart';
import 'package:eshi/app/shi/widget/CommonWidgets.dart';
import 'package:eshi/app/shi/widget/DocTextWidget.dart';
import 'package:eshi/app/shi/widget/VideoWidget.dart';
import 'package:flutter/material.dart';
import 'package:eshi/main.dart';
import 'package:eshi/app/shi/data/HistoryPoint.dart';
import 'package:eshi/app/shi/taxis/MarkText.dart';
import 'package:eshi/app/shi/taxis/TabEditPage.dart';
import 'package:eshi/app/shi/widget/AudioTextWidget.dart';
import 'package:eshi/app/shi/widget/ImageWidget.dart';
import 'package:eshi/app/shi/widget/IndentWidget.dart';
import 'package:eshi/app/shi/widget/RowStartWidget.dart';
import 'package:eshi/app/shi/widget/WebTextWidget.dart';

/// 数据分组展示 
/// 竖屏顶部 横屏左侧
class tabsWidget extends StatefulWidget{
  HistoryPoint point;
  final Function(tabsState)? onStateReady;
  tabsWidget(this.point, {super.key,this.onStateReady});
  @override
  State<StatefulWidget> createState()  => tabsState();
}

class tabsState extends State<tabsWidget>{
  int searchCount=0;
  int searchIndex=0;
  String searchKey="";
  late HistoryPoint point;
  late TabController tabController;
  Color? bgColor;
  @override
  initState(){
    point = widget.point;
    if(widget.onStateReady!=null){
      widget.onStateReady!(this);
    }
    ImageWidget.initContext(context);
    if(size>1 && point.history!.defaultPath.isNotEmpty && point.history!.defaultPath.contains("/")){
          var path = point.history!.defaultPath;
          var selectTab = point.data.keys.firstWhere((test) => path.endsWith(test));
          var tabIndex = point.data.keys.toList().indexOf(selectTab);
          setTimeout(() => switchTab(tabIndex) , 500);
          point.history!.defaultPath = "";
    }
    super.initState();
  }
  // 关键：监听父组件属性变化
  @override
  void didUpdateWidget(covariant tabsWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当父组件的 point 发生变化时
    if (widget.point != oldWidget.point) {
      
      setPoint(widget.point);
      taxisState?.tabState = this;
      
      Future.delayed(Duration(microseconds: 500)).then((_) {
        setState(() {});
      });
      // Config.lastHistory="";
    }
  }
  get size => point.data.length;
  get taxisState => customWidgetKey.currentState;

  get tabTitles  {
    List<Widget> rt =[];
    for(var k in point.data.keys){
        rt.add(Tab(text: k));
    }  
    return size>1
          ? 
           (System.isPhone) 
             ? TabBar(
              isScrollable: true,
              tabAlignment:TabAlignment.start,
              tabs:rt
             )
             :PreferredSize(
              preferredSize: const Size.fromHeight(65),
              child: Container(
                padding: EdgeInsets.only(top: 10,left: 10,right: 10),
                decoration: BoxDecoration(
                  color: bgColor ?? Colors.white,
                  //  border: Border(
                  //   bottom: BorderSide(color: Colors.transparent), // 透明边框覆盖默认线条
                  // ),
                ),
                child:  TabBar(
                  isScrollable: true,
                  tabAlignment:TabAlignment.start,
                  tabs:  rt,
                  labelColor: Colors.white,
                  unselectedLabelColor: Colors.black,
                  indicatorPadding: EdgeInsets.symmetric(horizontal: -15),
                  indicator: BoxDecoration(
                    color: Colors.black,
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(10), // 顶部圆角半径
                        // 底部不设置，保持默认直角
                      ),
                  ),
                )
              )
            )
          : PreferredSize(
              preferredSize: const Size.fromHeight(10),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: const Divider(height: 1),
              )
          );
  }

  get tabBodys  {
    List<Widget> rt =[];
    int toPageTopCount=0;
    int toPageButtomCount=0;
    // Icon(Icons.directions_car)
    for(var v in point.data.values){
        var myPage = NotificationListener<ScrollNotification>(
            onNotification: (notification) {
              // 监听子组件滚动状态，判断是否处于顶部/底部
              final scrollView = notification.metrics;
              if(scrollView.pixels <= 0){
                if(toPageTopCount++ ==10) {
                  taxisState?.upIndex(-1);
                }
              }
              if(scrollView.pixels >= scrollView.maxScrollExtent){
                if(toPageButtomCount++ ==10) {
                  taxisState?.upIndex(1);
                }
              }
              return false;
            },
            child: SingleChildScrollView(
              // 子组件内容（足够长以产生滚动）
              child: page(v)
            )
        );
        rt.add(
          // ParentDraggableWidget(child: page(v))
          System.isPhone ? Container(
                padding: EdgeInsets.all(10),
                child: myPage
          )
          :Container(
            padding: EdgeInsets.only(left: 10,right:10,bottom: 10),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15,vertical: 25),
              decoration: BoxDecoration(
                  color: bgColor,
                  border:Border(
                    bottom: BorderSide(color: Colors.grey.shade300,width: 1.0,),
                    left: BorderSide(color: Colors.grey.shade300,width: 1.0,),
                    right: BorderSide(color: Colors.grey.shade300,width: 1.0,),
                  ),
                  borderRadius: BorderRadius.vertical(
                    bottom: Radius.circular(10)
                  ),
                  // borderRadius:  BorderRadius.circular(10), // 顶部圆角半径
                  
              ),
              child: myPage
            )
          )
        );
    }  
    return rt;
  }

 

  Widget page(v){
      List<Widget> childs=[];
      point.history?.findMark(v,(dynamic type,String text,{String comment=''}){
        List<Widget> popWidgets = [];
        switch(type){
          case HistoryMarks.baike:
            childs.add(WebTextWidget(
              text:text,
              children:_Text(text,style:TextStyle(
                color: Colors.blue,
              ))
            ));
            // childs.add(Text(text));
            break;
          case "audio": //音频
          case HistoryMarks.audio:
            childs.add(AudioTextWidget(
              text: text,
              children:type==HistoryMarks.audio ?  _Text(text) :null,
            ));
            break;
          case "img": //图片  
          case "image": 
          case HistoryMarks.image:
            childs.add(
              ImageWidget.load(
                text,
                type == HistoryMarks.image ? _Text(text,style: TextStyle(color: Colors.teal)) : null
              )
            );
            break;  
          case "video": //视频
          case HistoryMarks.video:
            childs.add(
              VideoWidget(
                text : text,
                showChild: type == HistoryMarks.video,
                child:_Text(text,style: TextStyle(color: Colors.teal))
              )
            );
            break;
          case "doc": //文档
          case HistoryMarks.doc:
            childs.add(
              DocTextWidget(
                text:text,
                showChild: type == HistoryMarks.doc,
                child: _Text(text,style: TextStyle(color: Colors.lightBlue)),
              )
            );
            break;
          case "app": //安装包
          case HistoryMarks.app:
              childs.add(
                AppTextWidget(
                  text:text,
                  showChild: type == HistoryMarks.app,
                  child: _Text(text,style: TextStyle(color: Colors.lightBlueAccent))
                )
              );
            break;
          case "child": //折叠
            if(text==""){ //折叠返回 从列表中配置子元素  
                while(childs.last is! IndentWidget || (childs.last as IndentWidget).childs.isNotEmpty){
                  popWidgets.insert(0, childs.last);
                  childs.removeLast();
                }
                var lastIndentWidget = childs.last as IndentWidget;
                lastIndentWidget.appendChilds(popWidgets);
            }else{
              childs.add(
                IndentWidget(text:text)
              );
            }
            break;
          case "rowStart":
            childs.add(RowStartWidget());
            break;
          case "rowEnd":
              while(childs.isNotEmpty && childs.last is! RowStartWidget){
                  popWidgets.insert(0, childs.last);
                  childs.removeLast();
              }
              childs.removeLast(); 
              childs.add( Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                children: popWidgets
              ));
              break;
          case "uri":
            childs.add( InkWell(
              onTap: () => openUrl(text),
              child: _Text(text,style:TextStyle(color: Colors.blue))
            ));
          default:
            //文本整行
            childs.add(
                _Text(text,style:comment.isEmpty ? null: CommentParser.getTextStyle(comment))

            );
        }
      });
      return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: childs,
      );
      // return Text(v.toString());
  }
  
  Widget _Text(String text,{TextStyle? style}){
    return  searchKey.isEmpty ?  Text(text,style:style,): Text.rich(MarkText(text,searchKey,_selectNowPageIndex));
  }

   // 代码触发切换到指定标签页
  void switchTab(int index) {
    if (index >= 0 && index < tabController.length) {
      tabController.animateTo(index); // 带动画切换
      // 无动画切换：_tabController?.index = index;
      // Config.lastHistory="";
    }
  }
  
  int _selectNowPageIndex=0;
  void selectText(int index){
    _selectNowPageIndex = index;
  }

  void setPoint(HistoryPoint point) {
      setState(() {
        this.point = point;
      });
  }
  //修改引入的文件名 
  onChangeName(String type,text){
      prompt(text, (v){
        FileParser.rename(type,text,v);
        point.source = point.source.replaceAll(text, v);
        point.history?.marks[v] = point.history!.marks[text]!;
        point.history?.marks.remove(text);
        point.history?.save(point: point);
      });
  }
  //调弹框修改文本内容
  onChangeData(){
     if(HistoryConfig.isReadOnly(point.history?.name)){
        msgErr("本文档只读无法编辑！");
        return;
     }
      modeWindow(context,TabEditPage(
              title:point.name, 
              data: point.source,
              marks:point.hasMarks, 
              // tools:  Text("aaa"),
              onChange: (v,marks,title){
                customWidgetKey.currentState?.onPointChange(point,data:v,marks:marks);
                Navigator.pop(context);
                setState(() {
                  point = point;
                });
              })
      );
  }
  //跳转到搜索页面 
  onSearch(){
      customWidgetKey.currentState!.onSearch().then((sr){
          setState(() {
            searchIndex=0;
            searchCount = sr.count;
            searchKey = sr.key;
            customWidgetKey.currentState!.onSearchIndex(searchKey,index:searchIndex,state:this);
          });
      });
  }

  //tab切换 
  void onChangeTab(int add) {
    switchTab(tabController.index+add);
  }

  pageSetting(String type){
    switch(type){
      case "配置页":
         Navigator.pushNamed(context, '/settings');
         break;
      case "时间轴":
        taxisState?.onTimeLineButtonClick();
        break;
      case "内容编辑":
        onChangeData();
        break;
      case "搜索":
        onSearch();
        break;
      case "显示模式":
        simpleSetting(context: context, values: ["单页","多页","时间轴"], title:"显示模式",onChange: (name,i){
          point.history?.showMode = i+1;
          mainWidgetKey.currentState?.changeHistory(point.history!);
        });
      case "背景颜色":
        simpleSetting(context: context,title:"背景颜色", values: ["灰色","蓝色","白色","黑色"], onChange: (name,i){
          var colorMap={
            "灰色" : Colors.grey,
            "蓝色":Colors.blue,
            "白色":Colors.white24,
            "黑色" : Colors.black54
          };
          setState(() {
            bgColor = colorMap[name];
          });
        });  
    }
      // return Container(
      //     padding: EdgeInsets.all(10),
      //     child: Column(
      //       crossAxisAlignment: CrossAxisAlignment.start,
      //       children: [
      //         Text("显示模式"),
      //         const Divider(height: 1),
      //         Row(children: [

      //         ]),

      //         Text("背景颜色"),
      //         const Divider(height: 1),
      //         Wrap(children: [

      //         ])
      //     ],),
      // );
  }

  @override
  Widget build(BuildContext context) {
    markSize=0;
    return Container(
         color: bgColor,
        width: double.infinity,
        height: double.infinity,
        child:   DefaultTabController(
                length: size,
                child: Scaffold(
                    appBar: AppBar(
                        backgroundColor:System.isPhone ? null : Colors.black87, // 系统预设颜色
                        centerTitle: true,
                        title: DecoratedBox(
                            decoration: BoxDecoration(
                              // shape: BoxShape.rectangle, // 圆形
                              // color: Colors.white70,
                              // borderRadius: BorderRadius.circular(100),
                            ),
                            child:InkWell(
                              onTap: onChangeData,
                              // onLongPress: (){
                              //   simpleDialog(context: context, body: pageSetting(),title: "界面配置");
                              // },
                              child:  Padding(
                                padding: EdgeInsets.all(10.0),
                                child:  Text(point.name,style: System.isPhone ? null : TextStyle(fontSize: 30,color: Colors.white))
                            )),
                        ),
                        actions: [
                          Builder(builder: (context){
                            tabController = DefaultTabController.of(context);
                            tabController.addListener((){
                                point.tabIndex = tabController.index;
                            });
                            return Container();
                          }),
                          if(searchCount>0)
                          Builder(builder: (context){
                              return GestureDetector(
                                // onDoubleTap: () {
                                //   setState(() {
                                //     if(--searchIndex < 0) searchIndex=0;  
                                //   });
                                //   customWidgetKey.currentState!.onSearchIndex(searchKey,index:searchIndex,state:this);
                                // },
                                onLongPress: (){
                                  setState(() {
                                    searchIndex=0;
                                    searchCount = 0;
                                    searchKey = "";
                                  });
                                },
                                child: TextButton(
                                  onPressed: (){
                                    setState(() {
                                      if(++searchIndex >= searchCount) searchIndex=searchCount-1;  
                                    });
                                    markSize=0;
                                    customWidgetKey.currentState!.onSearchIndex(searchKey,index:searchIndex,state:this);
                                  },
                                  child:Text("${searchIndex+1}/$searchCount"),
                                ),
                            );
                          }),
                          Padding(
                            padding: EdgeInsets.only(right: 25),
                            child: IconButton(
                              icon: Icon(Icons.search),
                              onPressed: onSearch,
                            ),
                          )
                        ],
                        bottom:  tabTitles,
                    ),
                    body:TabBarView(
                            children: tabBodys,
                      )
                )
                )
        );
  }
  



}

